package com.hdl.script.logic.script.data

import android.content.Context
import com.hdl.script.model.Script
import com.hdl.script.model.ScriptType
import com.stardust.pio.PFiles
import org.json.JSONObject

class AssertScriptData : IScriptData {

    override fun handler(context: Context, data: String): MutableList<Script>? {
        return searchAssertFile(context, data.replace("assert:", ""))
    }

    private fun searchAssertFile(context: Context, dir: String): MutableList<Script>? {
        val childDirs = context.assets.list(dir)
        if (childDirs?.isNotEmpty() == true) {
            val scripts = ArrayList<Script>()
            for (childDir in childDirs) {
                val childObj = searchProjectJson(context, "${dir}/${childDir}")
                if (childObj != null) {
                    val name = childObj.optString("name")
                    val main = childObj.optString("main")
                    val versionCode = childObj.optInt("versionCode")
                    val versionName = childObj.optString("versionName")
                    if (main?.isNotEmpty() == true && name?.isNotEmpty() == true) {
                        val script = Script(name = name, main = main,
                                type = ScriptType.ASSERT_TYPE, path = "${dir}/${childDir}",
                                versionCode = versionCode, versionName = versionName)
                        scripts.add(script)
                    }
                }
            }
            if (scripts.isNotEmpty()) {
                return scripts
            }
        }
        return null
    }

    private fun searchProjectJson(context: Context, dir: String): JSONObject? {
        try {
            val fileName = "${dir}/project.json"
            val input = context.assets.open(fileName)
            val content = PFiles.read(input, "UTF-8")
            if (content?.isNotEmpty() == true) {
                val contentObj = JSONObject(content)
                val main = contentObj.optString("main")
                if (main?.isNotEmpty() == true) {
                    val mainInput = context.assets.open("${dir}/${main}")
                    mainInput.close()
                    return contentObj
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}